//
//  SYJPictureView.swift
//  weibo
//
//  Created by 孙英建 on 16/4/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// cell 重用标识
private let key = "item"
// cell 间距
private let itemMargin: CGFloat = 5
// cell 的宽高
private let cellWH: CGFloat = (kWidth - 20 - itemMargin * 2) / 3

class SYJPictureView: UICollectionView {

    // 保存数据
    var pictureInfo: [SYJPictureInfoModel]?{
        didSet{
            
//            countLabel.text = "\(pictureInfo?.count ?? 0)"
            let size = getPictureViewSize(pictureInfo?.count ?? 0)
            
            // 更改自己的约束 没有涉及到被人来约束的 需要使用update 更简单
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            
            self.reloadData()
            
  
        }
    }
    
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置配图的大小
    func getPictureViewSize(count: Int) -> CGSize{
       // 行列数
        let col = count > 3 ? 3 : count
        let row = (count - 1) / 3 + 1
        
        // 配图的宽高
        let width = CGFloat(col) * cellWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * cellWH + CGFloat(row - 1) * itemMargin
        
        return CGSize(width: width, height: height)
    }
    
    
    // 设置UI
    func setUI(){
        
        self.backgroundColor = UIColor.clearColor()
        
        // 注册cell
        registerClass(SYJPictureViewCell.self, forCellWithReuseIdentifier: key)
        
        dataSource = self
        delegate = self
        
        //设置布局
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
        
        // 添加label
//        addSubview(countLabel)
        
//        countLabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(self)
//        }
    }
    
    
    // MARK: - 懒加载控件
//    private lazy var countLabel: UILabel = {
//        let cl = UILabel()
//        cl.font = UIFont.systemFontOfSize(34)
//        cl.textColor = UIColor.redColor()
//        return cl
//    }()
    
}

// MARK: - 数据源方法
extension SYJPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfo?.count ?? 0
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(key, forIndexPath: indexPath) as! SYJPictureViewCell
        
        cell.pic = pictureInfo![indexPath.item]

        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = self.pictureInfo!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    
}

// 设置点击图片方法的代理
extension SYJPictureView: SDPhotoBrowserDelegate{
    
    // 返回临时站位图--原来的小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = cellForItemAtIndexPath(indexPath) as! SYJPictureViewCell
        return cell.bgImageView.image
    }
    
    // 返回高质量的大图的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlStr = (self.pictureInfo![index].thumbnail_pic ?? "" as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
    }
    
}



// 自定义cell
class SYJPictureViewCell: UICollectionViewCell {
    
    var pic: SYJPictureInfoModel?{
        didSet{
             bgImageView.sd_setImageWithURL(NSURL(string: pic?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_card_top_background"))
            
            // 判断是否动态图
            if let p = pic?.thumbnail_pic where p.hasSuffix(".gif") {
                bgImageView.hidden = false
            }else{
                // 不是动态图
                gifImageView.hidden = true
            }
        }
    }
    
    
     override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
    }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }

    
    // 设置UI
    private func setUI(){
        
        self.backgroundColor = UIColor.whiteColor()
        
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        
        // 约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.bottom.equalTo(contentView)
        }
    }
    
    
    // MARK: - 懒加载控件
    
    // 背景图片
    private lazy var bgImageView: UIImageView = {
       let bgV = UIImageView(image: UIImage(named: "timeline_card_top_background"))
        bgV.contentMode = .ScaleAspectFill
        bgV.clipsToBounds = true
        return bgV
    }()
    
    // 动图logo
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))


}






















